//
//  YWPopView.m
//  maintain
//
//  Created by 郑想 on 15/10/19.
//  Copyright © 2015年 ewin. All rights reserved.
//

#import "DropDownListViewController.h"
#import "UIColor+CustomColors.h"
#import "UIImage+Extension.h"
#import "UIView+Extension.h"
#import "YWAssignMemberListTableViewController.h"
#import "YWEquipment.h"
#import "YWMacro.h"
#import "YWPopView.h"
#import "YWSelectListOfTempmissionTableVC.h"
#import "YWSelectMonthListTableViewController.h"
#import "YWShowRulesTableViewController.h"
#import "YWRuntimeOptionsTableViewController.h"
#import "YWMaterialPopListTableViewController.h"
#import <POP/POP.h>

#define kAlertWidth (SCREEN_WIDTH * 0.8)
#define kAlertHeight 340.0f

@interface YWPopView () <UIViewControllerTransitioningDelegate, DropDownListDelegate, YWAssignMemberListDelegate, YWSelectListOfTempmissionDelegate, YWSelectMonthListDelegate,YWRuntimeOptionDelegate> {
    BOOL _leftLeave;
    CGFloat assignListViewH;
    CGFloat tempmissionH;
    CGFloat monthListViewH;
    CGFloat ruleListH;
    CGFloat runtimeOptionH;
    CGFloat materialH;
}

@property (nonatomic, strong) UILabel* alertTitleLabel;
//@property (nonatomic, strong) UILabel* alertContentLabel;
//@property (nonatomic, strong) UIButton* leftBtn;
//@property (nonatomic, strong) UIButton* rightBtn;
@property (nonatomic, strong) UIView* backImageView;
@property (nonatomic, strong) DropDownListViewController* ddList;
@property (nonatomic, strong) YWAssignMemberListTableViewController* assignList;
@property (nonatomic, strong) YWSelectListOfTempmissionTableVC* selectListOfTempmission;
@property (nonatomic, strong) YWSelectMonthListTableViewController* monthList;
@property (nonatomic, strong) YWShowRulesTableViewController* ruleList;
@property (nonatomic, strong) YWRuntimeOptionsTableViewController* optionList;
@property (nonatomic, strong) YWMaterialPopListTableViewController * materialList;
@end

@implementation YWPopView

//+ (CGFloat)alertWidth
//{
//    return kAlertWidth;
//}
//
//+ (CGFloat)alertHeight
//{
//    return kAlertHeight;
//}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self commonSetUp];
    }
    return self;
}
#pragma mark - DropDownListDelegate
- (void)selectValue:(NSInteger)reasonId andContent:(NSString*)content
{
    [self dismissAlert];
    if ([self.delegate respondsToSelector:@selector(popValue:andContent:)]) {
        [self.delegate popValue:reasonId andContent:content];
    }
}

- (DropDownListViewController*)ddList
{
    if (!_ddList) {
        _ddList = [[DropDownListViewController alloc] initWithStyle:UITableViewStylePlain];
        _ddList.delegate = self;
        [self addSubview:_ddList.view];
    }
    return _ddList;
}

#pragma mark - YWAssignMemberListDelegate
- (void)selectHandler:(YWHandler*)handler
{
    [self dismissAlert];
    if ([self.delegate respondsToSelector:@selector(popHandler:)]) {
        [self.delegate popHandler:handler];
    }
}
- (YWAssignMemberListTableViewController*)assignList
{
    if (!_assignList) {
        _assignList = [[YWAssignMemberListTableViewController alloc] initWithStyle:UITableViewStylePlain];
        _assignList.delegate = self;
        //        _assignList.handlers = self.handlers;
        [self addSubview:_assignList.view];
    }
    return _assignList;
}
#pragma mark - YWSelectListOfTempmissionDelegate
- (void)selectQrcodeEquipment:(YWQrcodeEquipmentInfo*)qrcodeEquipmentInfo equipment:(YWEquipment*)equipment
{
    [self dismissAlert];
    if ([self.delegate respondsToSelector:@selector(popQrcodeEquipmentInfo:equipment:)]) {
        [self.delegate popQrcodeEquipmentInfo:qrcodeEquipmentInfo equipment:equipment];
    }
}

- (YWSelectListOfTempmissionTableVC*)selectListOfTempmission
{
    if (!_selectListOfTempmission) {
        _selectListOfTempmission = [[YWSelectListOfTempmissionTableVC alloc] initWithStyle:UITableViewStylePlain];
        _selectListOfTempmission.delegate = self;
        [self addSubview:_selectListOfTempmission.view];
    }
    return _selectListOfTempmission;
}
#pragma mark - YWSelectMonthListDelegate
- (void)selectMonth:(NSString*)month
{
    [self dismissAlert];
    if ([self.delegate respondsToSelector:@selector(popMonthValue:)]) {
        [self.delegate popMonthValue:month];
    }
}

- (void)materialListBack:(YWMaterial *)material{
    [self dismissAlert];
    
}

- (YWSelectMonthListTableViewController*)monthList
{
    if (!_monthList) {
        _monthList = [[YWSelectMonthListTableViewController alloc] initWithStyle:UITableViewStylePlain];
        _monthList.delegate = self;
        [self addSubview:_monthList.view];
    }
    return _monthList;
}

- (YWMaterialPopListTableViewController*)materialList
{
    if (!_materialList) {
        _materialList = [[YWMaterialPopListTableViewController alloc] initWithStyle:UITableViewStylePlain];
        [self addSubview:_materialList.view];
    }
    return _materialList;
}

- (YWShowRulesTableViewController *)ruleList{
    if (!_ruleList) {
        _ruleList = [[YWShowRulesTableViewController alloc] init];
        [self addSubview:_ruleList.view];
    }
    return _ruleList;
}
-(void)selectOption:(YWEquipmentFieldOption *)option{
    [self dismissAlert];
    if ([self.delegate respondsToSelector:@selector(popRuntimeOption:)]) {
        [self.delegate popRuntimeOption:option];
    }
}
- (YWRuntimeOptionsTableViewController *)optionList{
    if (!_optionList) {
        _optionList = [[YWRuntimeOptionsTableViewController alloc] init];
        _optionList.delegate = self;
        [self addSubview:_optionList.view];
    }
    return _optionList;
}
#define kTitleYOffset 15.0f
#define kTitleHeight 25.0f

#define kContentOffset 30.0f
#define kBetweenLabelOffset 20.0f

- (instancetype)initTroubleReasonWithTitle:(NSString*)title
{
    if (self = [super init]) {
        [self commonSetUp];
        self.alertTitleLabel.text = title;

        CGFloat contentLabelWidth = kAlertWidth - 16;
        [self.ddList.view setFrame:CGRectMake((kAlertWidth - contentLabelWidth) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), contentLabelWidth, 280)];
        //在下面的willMoveToSuperview方法里还需要重新设置frame，否则界面的宽高不对。
    }
    return self;
}

- (instancetype)initAssignMemberWithTitle:(NSString*)title handler:(NSArray*)handlers
{
    if (self = [super init]) {
        [self commonSetUp];
        self.alertTitleLabel.text = title;

        CGFloat contentLabelWidth = kAlertWidth - 16;
        self.assignList.handlers = handlers;
        if (handlers.count <= 3) {
            //行高是40
            assignListViewH = 3 * 40;
        }
        else if (handlers.count <= 6) {
            assignListViewH = handlers.count * 40;
        }
        else {
            //因为故障原因有7种
            assignListViewH = 7 * 40;
        }
        [self.assignList.view setFrame:CGRectMake((kAlertWidth - contentLabelWidth) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), contentLabelWidth, assignListViewH)];
        //在下面的willMoveToSuperview方法里还需要重新设置frame，否则界面的宽高不对。
    }
    return self;
}
- (instancetype)initTempmissionSelectWithTitle:(NSString*)title qrcodeEquipmentInfoArray:(NSArray*)qrcodeEquipmentInfoArray maintenanceType:(NSInteger)maintenanceType
{
    if (self = [super init]) {
        [self commonSetUp];
        self.alertTitleLabel.text = title;

        CGFloat contentLabelWidth = kAlertWidth - 16;
        self.selectListOfTempmission.qrcodeEquipmentInfoArray = qrcodeEquipmentInfoArray;
        self.selectListOfTempmission.maintenanceType = maintenanceType;
        __block NSInteger count = 0;
        if (maintenanceType == YWMaintenanceTypeTrouble) {
            [qrcodeEquipmentInfoArray enumerateObjectsUsingBlock:^(YWQrcodeEquipmentInfo* _Nonnull qrcodeEquipmentInfo, NSUInteger idx, BOOL* _Nonnull stop) {
                count += qrcodeEquipmentInfo.equipmentCount;
            }];
        }
        else {
            count = qrcodeEquipmentInfoArray.count;
        }

        if (count <= 3) {
            //行高是40
            tempmissionH = 3 * 40;
        }
        else if (count <= 6) {
            tempmissionH = count * 40;
        }
        else {
            //因为故障原因有7种
            tempmissionH = 7 * 40;
        }
        [self.selectListOfTempmission.view setFrame:CGRectMake((kAlertWidth - contentLabelWidth) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), contentLabelWidth, tempmissionH)];
        //在下面的willMoveToSuperview方法里还需要重新设置frame，否则界面的宽高不对。
    }
    return self;
}

- (instancetype)initMonthWithDays:(NSArray*)months
{
    if (self = [super init]) {
        [self commonSetUp];
        self.alertTitleLabel.text = @"请选择月份";
        self.monthList.months = months;
        CGFloat contentLabelWidth = kAlertWidth - 16;
        monthListViewH = 7 * 40;

        [self.monthList.view setFrame:CGRectMake((kAlertWidth - contentLabelWidth) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), contentLabelWidth, monthListViewH)];
        //在下面的willMoveToSuperview方法里还需要重新设置frame，否则界面的宽高不对。
    }
    return self;
}

- (instancetype)initReturnBackWithTitle:(NSString *)title Materials:(NSArray *)materialsArray type:(NSString*)type{
    if (self = [super init]) {
//        [self commonSetUp];
        self.alertTitleLabel.text = title;
        self.materialList.materialsReturn = materialsArray;
        CGFloat contentLabelWidth = kAlertWidth - 16;
        materialH = 7 * 40;
        
        [self.materialList.view setFrame:CGRectMake((kAlertWidth - contentLabelWidth) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), contentLabelWidth, materialH-kButtonH-10)];
        
        UIButton *sureButton = [self sureButton];
        if ([type isEqualToString:@"领用"]) {
            sureButton.tag = 1001;
        }else{
            sureButton.tag = 1002;
        }
        sureButton.frame = CGRectMake((kAlertWidth - contentLabelWidth) * 0.5+10, CGRectGetMaxY(self.materialList.view.frame)+10, contentLabelWidth-10*2, kButtonH);
        [self addSubview:sureButton];
        //在下面的willMoveToSuperview方法里还需要重新设置frame，否则界面的宽高不对。
    }
    return self;
}
- (UIButton *)sureButton{
    UIButton* sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sureButton setBackgroundColor:[UIColor customBlueColor]];
    [sureButton setTitle:@"确定" forState:UIControlStateNormal];
    sureButton.titleLabel.font = kBoldTitleFont;
    [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureButton.clipsToBounds = YES;
    sureButton.layer.cornerRadius = 5.0;
    [sureButton addTarget:self action:@selector(handleCerturnBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
    return sureButton;
}

- (void)handleCerturnBtnEvent:(UIButton *)sender{
    [self dismissAlert];
    if (sender.tag == 1001) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"KMaterialStockCerturnNotic" object:nil];
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"KmaterialListBack" object:nil];
    }
    
}
- (instancetype)initRulesWithTitle:(NSString*)title ruleArray:(NSArray*)rulesArray{
    if (self = [super init]) {
        [self commonSetUp];
        self.alertTitleLabel.text = title?:@"维保规则";
        self.ruleList.rulesArray = rulesArray;
        CGFloat contentLabelWidth = kAlertWidth - 16;
        ruleListH = (rulesArray.count <= 6? rulesArray.count : 7) * 40;
        
        [self.ruleList.view setFrame:CGRectMake((kAlertWidth - contentLabelWidth) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), contentLabelWidth, ruleListH)];
        //在下面的willMoveToSuperview方法里还需要重新设置frame，否则界面的宽高不对。
    }
    return self;
}
-(void)setOptionArray:(NSArray *)optionArray{
    _optionArray = optionArray;
    self.alertTitleLabel.text = @"请选择";
    CGFloat contentLabelWidth = kAlertWidth - 16;
    self.optionList.optionArray = optionArray;
    if (optionArray.count <= 3) {
        //行高是40
        runtimeOptionH = 3 * 40;
    }
    else if (optionArray.count <= 6) {
        runtimeOptionH = optionArray.count * 40;
    }
    else {
        //因为故障原因有7种
        runtimeOptionH = 7 * 40;
    }
    [self.optionList.view setFrame:CGRectMake((kAlertWidth - contentLabelWidth) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), contentLabelWidth, runtimeOptionH)];
    //在下面的willMoveToSuperview方法里还需要重新设置frame，否则界面的宽高不对。
}

- (void)commonSetUp
{
    self.clipsToBounds = YES;
    self.layer.cornerRadius = 5.0;
    self.backgroundColor = [UIColor whiteColor];
    self.alertTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, kTitleYOffset, kAlertWidth, kTitleHeight)];
    self.alertTitleLabel.font = [UIFont boldSystemFontOfSize:20.0f];
    self.alertTitleLabel.textColor = [UIColor colorWithRed:56.0 / 255.0 green:64.0 / 255.0 blue:71.0 / 255.0 alpha:1];
    [self addSubview:self.alertTitleLabel];
    self.alertTitleLabel.textAlignment = NSTextAlignmentCenter;

    UIButton* xButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [xButton setImage:[UIImage imageNamed:@"btn_close_normal.png"] forState:UIControlStateNormal];
    [xButton setImage:[UIImage imageNamed:@"btn_close_selected.png"] forState:UIControlStateHighlighted];
    xButton.frame = CGRectMake(kAlertWidth - 32, 0, 32, 32);
    [self addSubview:xButton];
    [xButton addTarget:self action:@selector(dismissAlert) forControlEvents:UIControlEventTouchUpInside];

    self.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
}
- (void)leftBtnClicked:(id)sender
{
    _leftLeave = YES;
    [self dismissAlert];
    if (self.leftBlock) {
        self.leftBlock();
    }
}

- (void)rightBtnClicked:(id)sender
{
    _leftLeave = NO;
    [self dismissAlert];
    if (self.rightBlock) {
        self.rightBlock();
    }
}

- (void)show
{
    UIViewController* topVC = [self appRootViewController];
    CGRect rect;
    if (_ddList) {
        rect = CGRectMake((CGRectGetWidth(topVC.view.bounds) - kAlertWidth) * 0.5, -kAlertHeight - 30, kAlertWidth, kAlertHeight);
    }
    else if (_assignList) {
        CGFloat selfH = assignListViewH + kTitleYOffset + kTitleHeight + 20;
        rect = CGRectMake((CGRectGetWidth(topVC.view.bounds) - kAlertWidth) * 0.5, -selfH - 30, kAlertWidth, selfH);
    }
    else if (_monthList) {
        CGFloat selfH = monthListViewH + kTitleYOffset + kTitleHeight + 20;
        rect = CGRectMake((CGRectGetWidth(topVC.view.bounds) - kAlertWidth) * 0.5, -selfH - 30, kAlertWidth, selfH);
    }else if (_materialList) {
        CGFloat selfH = materialH + kTitleYOffset + kTitleHeight + 20;
        rect = CGRectMake((CGRectGetWidth(topVC.view.bounds) - kAlertWidth) * 0.5, -selfH - 30, kAlertWidth, selfH);
    }else if (_ruleList){
        CGFloat selfH = ruleListH + kTitleYOffset + kTitleHeight + 20;
        rect = CGRectMake((CGRectGetWidth(topVC.view.bounds) - kAlertWidth) * 0.5, -selfH - 30, kAlertWidth, selfH);
    }else if (_optionList){
        CGFloat selfH = runtimeOptionH + kTitleYOffset + kTitleHeight + 20;
        rect = CGRectMake((CGRectGetWidth(topVC.view.bounds) - kAlertWidth) * 0.5, -selfH - 30, kAlertWidth, selfH);
    }
    else {
        CGFloat selfH = tempmissionH + kTitleYOffset + kTitleHeight + 20;
        rect = CGRectMake((CGRectGetWidth(topVC.view.bounds) - kAlertWidth) * 0.5, -selfH - 30, kAlertWidth, selfH);
    }
    self.frame = rect;
    [topVC.view addSubview:self];
}

- (void)dismissAlert
{
    [self removeFromSuperview];
    if (self.dismissBlock) {
        self.dismissBlock();
    }
}

- (UIViewController*)appRootViewController
{
    UIViewController* appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController* topVC = appRootVC;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}

- (void)removeFromSuperview
{
    POPBasicAnimation* opacityAnimation = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerOpacity];
    opacityAnimation.toValue = @(0.0);
    [opacityAnimation setCompletionBlock:^(POPAnimation* anim, BOOL finished) {
        [self.backImageView removeFromSuperview];
        self.backImageView = nil;
    }];

    POPBasicAnimation* offscreenAnimation = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerPositionY];
    offscreenAnimation.toValue = @(-self.backImageView.layer.position.y);
    [offscreenAnimation setCompletionBlock:^(POPAnimation* anim, BOOL finished) {
        [super removeFromSuperview];
    }];
    [self.layer pop_addAnimation:offscreenAnimation forKey:@"offscreenAnimation"];
    [self.backImageView.layer pop_addAnimation:opacityAnimation forKey:@"opacityAnimation"];
}

- (void)willMoveToSuperview:(UIView*)newSuperview
{
    if (newSuperview == nil) {
        return;
    }
    if (_ddList) {
        [self.ddList.view setFrame:CGRectMake((kAlertWidth - (kAlertWidth - 16)) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), kAlertWidth - 16, 280)];
    }
    else if (_assignList) {
        [self.assignList.view setFrame:CGRectMake((kAlertWidth - (kAlertWidth - 16)) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), kAlertWidth - 16, assignListViewH)];
    }
    else if (_monthList) {
        [self.monthList.view setFrame:CGRectMake((kAlertWidth - (kAlertWidth - 16)) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), kAlertWidth - 16, monthListViewH)];
    }
    else if (_materialList) {
        [self.materialList.view setFrame:CGRectMake((kAlertWidth - (kAlertWidth - 16)) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), kAlertWidth - 16, materialH-kButtonH-10)];
    }else if (_ruleList){
        [self.ruleList.view setFrame:CGRectMake((kAlertWidth - (kAlertWidth - 16)) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), kAlertWidth - 16, ruleListH)];
    }else if (_optionList){
        [self.optionList.view setFrame:CGRectMake((kAlertWidth - (kAlertWidth - 16)) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), kAlertWidth - 16, runtimeOptionH)];
    }
    else {
        [self.selectListOfTempmission.view setFrame:CGRectMake((kAlertWidth - (kAlertWidth - 16)) * 0.5, CGRectGetMaxY(self.alertTitleLabel.frame), kAlertWidth - 16, tempmissionH)];
    }

    UIViewController* topVC = [self appRootViewController];

    if (!self.backImageView) {
        self.backImageView = [[UIView alloc] initWithFrame:topVC.view.bounds];
        self.backImageView.backgroundColor = [UIColor blackColor];
        self.backImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    }
    [topVC.view addSubview:self.backImageView];

    POPSpringAnimation* positionAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionY];
    positionAnimation.toValue = @(CGRectGetHeight(topVC.view.bounds) * 0.5);
    positionAnimation.springBounciness = 10;

    POPSpringAnimation* scaleAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerScaleXY];
    scaleAnimation.springBounciness = 20;
    scaleAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(1.2, 1.4)];

    POPBasicAnimation* opacityAnimation = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerOpacity];
    opacityAnimation.toValue = @(0.6);

    [self.layer pop_addAnimation:positionAnimation forKey:@"positionAnimation"];
    [self.layer pop_addAnimation:scaleAnimation forKey:@"scaleAnimation"];
    [self.backImageView.layer pop_addAnimation:opacityAnimation forKey:@"opacityAnimation"];

    [super willMoveToSuperview:newSuperview];
}

@end
